package config

import (
	"DCOS-API/utils"
	"encoding/json"
	"fmt"
	"github.com/jinzhu/configor"
	"github.com/jinzhu/gorm"
	"os"
	"sync"
	"time"
)

type Config struct {
	BaseConfig baseConfYaml `json:"-"`
	Mysql   struct {
		Addr        string `yaml:"Addr" json:"addr"`
		User        string `yaml:"User" json:"user"`
		Pass        string `yaml:"Pass" json:"pass"`
		DB          string `yaml:"DB" json:"db"`
		Active      int    `yaml:"Active" json:"active"`
		Idle        int    `yaml:"Idle" json:"idle"`
		IdleTimeout int    `yaml:"IdleTimeout" json:"idle_timeout"`
	} `yaml:"Mysql" json:"mysql"`
	Redis struct {
		Addr         string `yaml:"Addr" json:"addr"`
		Password     string `yaml:"Password" json:"password"`
		DB           int    `yaml:"DB" json:"db"`
		Idle         int    `yaml:"Idle" json:"idle"`
		MaxConnAge   int    `yaml:"MaxConnAge" json:"max_conn_age"`
		DialTimeout  int    `yaml:"DialTimeout" json:"dial_timeout"`
		ReadTimeout  int    `yaml:"ReadTimeout" json:"read_timeout"`
		WriteTimeout int    `yaml:"WriteTimeout" json:"write_timeout"`
		IdleTimeout  int    `yaml:"IdleTimeout" json:"idle_timeout"`
	} `yaml:"Redis" json:"redis"`

}


type baseConfYaml struct {
	ENV        string `yaml:"ENV"`
	HOST       string `yaml:"HOST"`
	PORT       int    `yaml:"PORT"`
	SignKey     string `yaml:"SignKey"`
	Timestamp  int    `yaml:"Timestamp"`
	LimitSpeed int    `yaml:"LimitSpeed"`
	LogPath    string `yaml:"LogPath"`
	ConfDB     struct {
		Addr        string `yaml:"Addr"`
		User        string `yaml:"User"`
		Pass        string `yaml:"Pass"`
		DB          string `yaml:"DB"`
	} `yaml:"ConfDB"`
}

type baseConf struct {
	ID     int    `json:"id"`
	ENV    string `json:"env"`
	Config string `json:"config"`
}

func (b *baseConf) TableName() string {
	return "base_conf"
}

var (
	confPath string
	conf     *Config
	once     sync.Once
)

func init() {
	env := os.Getenv("ENV")
	fmt.Printf("ENV: %v\n", env)
	if env == "pro" {
		confPath = "./config.yaml"
	} else if env == "dev" {
		confPath = "./config.dev.yaml"
	} else {
		confPath = "/home/kubenetes/文档/go-work/DCOS-API/config.dev.yaml"
	}
}

func GetConfig() *Config {
	once.Do(func() {
		var err error
		bcy := new(baseConfYaml)
		err = configor.New(&configor.Config{AutoReload: false, AutoReloadInterval: time.Second * 5}).Load(bcy, confPath)
		if err != nil {
			panic(err)
		}
		dbc := bcy.ConfDB
		dbc.Pass, err = utils.AesDe(dbc.Pass, bcy.SignKey)
		if err != nil {
			panic(fmt.Errorf("解密mysql密码(%v)错误！", dbc.Pass))
		}
		url := fmt.Sprintf(dbc.Addr, dbc.User, dbc.Pass, dbc.DB)
		db, err := gorm.Open("mysql", url)
		if err != nil {
			panic(err)
		}
		defer db.Close()
		db.LogMode(true)
		bc := new(baseConf)
		if notFound := db.First(bc, "env = ?", bcy.ENV).RecordNotFound(); notFound {
			panic(fmt.Sprintf("%v 配置文件缺失！\n", bcy.ENV))
		}
		conf = new(Config)
		if err := json.Unmarshal([]byte(bc.Config), conf); err != nil {
			panic(fmt.Sprintf("配置文件解析失败：%v\n", err.Error()))
		}
		conf.BaseConfig = *bcy
		fmt.Println("--------config-----------")
		fmt.Printf("%+v\n", conf)
		fmt.Println("-------------------------")
	})
	return conf
}
